import express, { Request, Response, Router } from 'express';
import { PrismaClient } from '@prisma/client';
import { authMiddleware } from '../middleware/auth';
import { ApiResponse } from '../utils/response';

const router: Router = express.Router();
const prisma = new PrismaClient();

// 获取市场概览
router.get('/overview', authMiddleware, async (req: Request, res: Response): Promise<void> => {
  try {
    // 这些数据可以从外部API获取或数据库中存储
    const marketOverview = {
      marketCap: 2850000000000, // NEAR市值（韩元）
      volume24h: 180000000000, // 24小时交易量
      circulatingSupply: 1100000000, // 流通供应量
      totalSupply: 1200000000, // 总供应量
      rank: 24 // 市值排名
    };

    res.json(ApiResponse.success(marketOverview, '시장 개요 조회에 성공했습니다.'));
  } catch (error) {
    console.error('시장 개요 조회 오류:', error);
    res.status(500).json(ApiResponse.error('시장 개요 조회에 실패했습니다.'));
  }
});

// 获取NEAR当前价格
router.get('/near-price', authMiddleware, async (req: Request, res: Response): Promise<void> => {
  try {
    const { priceService } = await import('../services/priceService');
    const priceData = await priceService.getNearPriceData();

    res.json(ApiResponse.success({
      price: priceData.price,
      change24h: priceData.change24h,
      changeRate24h: priceData.changeRate24h,
      lastUpdate: priceData.lastUpdate
    }, 'NEAR 가격 조회에 성공했습니다.'));
  } catch (error) {
    console.error('NEAR 가격 조회 오류:', error);
    res.status(500).json(ApiResponse.error('NEAR 가격 조회에 실패했습니다.'));
  }
});

// 获取收益趋势数据
router.get('/trends', authMiddleware, async (req: Request, res: Response): Promise<void> => {
  try {
    const userId = (req as any).userId;
    const { days = 30 } = req.query;

    // 获取用户的奖励历史数据
    const rewardHistory = await prisma.stakingReward.findMany({
      where: {
        userId,
        createdAt: {
          gte: new Date(Date.now() - Number(days) * 24 * 60 * 60 * 1000)
        }
      },
      orderBy: { createdAt: 'asc' }
    });

    // 按日期聚合数据
    const trendData = [];
    const dateMap = new Map();

    // 初始化所有日期
    for (let i = Number(days) - 1; i >= 0; i--) {
      const date = new Date(Date.now() - i * 24 * 60 * 60 * 1000);
      const dateStr = date.toISOString().slice(5, 10); // MM-DD格式
      dateMap.set(dateStr, 0);
    }

    // 聚合实际奖励数据
    rewardHistory.forEach(reward => {
      const dateStr = reward.createdAt.toISOString().slice(5, 10);
      const nearPrice = 6500; // NEAR价格
      const krwAmount = Number(reward.amount) * nearPrice;
      dateMap.set(dateStr, (dateMap.get(dateStr) || 0) + krwAmount);
    });

    // 转换为数组格式
    dateMap.forEach((rewards, date) => {
      trendData.push({
        date,
        rewards: Math.round(rewards)
      });
    });

    // 如果没有历史数据，生成模拟趋势数据
    if (rewardHistory.length === 0) {
      const baseReward = 3500; // 基础日奖励
      for (let i = Number(days) - 1; i >= 0; i--) {
        const date = new Date(Date.now() - i * 24 * 60 * 60 * 1000);
        const dateStr = date.toISOString().slice(5, 10);
        const variation = (Math.random() - 0.5) * 1000; // ±500韩元波动
        const rewards = Math.max(0, baseReward + variation);

        trendData.push({
          date: dateStr,
          rewards: Math.round(rewards)
        });
      }
    }

    res.json(ApiResponse.success(trendData, '수익 추세 조회에 성공했습니다.'));
  } catch (error) {
    console.error('수익 추세 조회 오류:', error);
    res.status(500).json(ApiResponse.error('수익 추세 조회에 실패했습니다.'));
  }
});

export default router;